<template>
  <div class="content">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="130px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-form-item label="所属学校" prop="schoolId">
        <el-select
          v-model="ruleForm.schoolId"
          :disabled="userInfo.deptId!=null"
          @change="getShiTang"
          size="mini"
          clearable
          placeholder="请选择学校">

          <el-option v-for="item in schoolList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属食堂" prop="shitangId">
        <el-select v-model="ruleForm.shitangId" size="mini" clearable placeholder="请选择食堂">
          <el-option v-for="item in shitangList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="档口名称" prop="name">
        <el-input class="title" v-model="ruleForm.name" placeholder="请输入档口名称" clearable></el-input>
      </el-form-item>

      <el-form-item label="档口编号" prop="shopNo">
        <el-input class="title" v-model="ruleForm.shopNo" placeholder="请输入档口编号" clearable></el-input>
      </el-form-item>

      <el-form-item label="限制消费次数" prop="limitCount">
        <el-input class="title" v-model="ruleForm.limitCount" placeholder="请输入限制消费次数，不填不限制" clearable></el-input>
      </el-form-item>

      <el-form-item label="限制消费金额" prop="limitAmount">
        <el-input class="title" v-model="ruleForm.limitAmount" placeholder="请输入限制消费金额，不填不限制" clearable></el-input>
      </el-form-item>


      <el-form-item label="学生餐费标准">
        <div>
          <el-table
            height="400"
            :span-method="objectSpanMethod"
            :data="tableData"
            border
            style="width: 100%"
            size="mini"
          >
            <el-table-column prop="weekTime" label="星期"></el-table-column>
            <el-table-column prop="can" label="用餐时段"></el-table-column>
            <el-table-column prop="address" label="学生价格（元）">
              <template slot-scope="scope">
                <el-input v-model="price['student'+scope.$index]" placeholder="请输入价格"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="教师价格（元）">
              <template slot-scope="scope">
                <el-input v-model="price['teacher'+scope.$index]" placeholder="请输入价格"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-form-item style="margin-top: 20px">
        <el-button @click="resetForm('ruleForm')">{{$t("action.reset")}}</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="upluadStatus">{{$t("action.save")}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { format } from "@/utils/datetime";
import DangKouList from "@/assets/js/DangKouList";
import DangKouInput from "@/assets/js/DangKouInput";

export default {
  name: "edit",
  props: {
    msg: ""
  },
  data() {
    return {
      url: this.$Config.url,
      id: "",
      userInfo: {},
      upluadStatus:false,
      price: {},
      marketList: [], //食堂列表
      schoolList: [], //学校数据
      shitangList: [], //食堂数据
      mealDtos: [], //查询的单个数据
      ruleForm: {
        schoolId: "",
        shitangId: "", //食堂id
        name: "", //名称
        cadre: "", //食堂负责人
        shopNo: "", //食堂编号
        limitCount: "",//限制消费次数
        limitAmount: ""//限制消费金额
      },
      rules: {
        name: [
          { required: true, message: "请输入档口名称", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" }
        ],
        schoolId: [
          { required: true, message: "请选择学校", trigger: "change" }
        ],
        shitangId: [
          { required: true, message: "请选择食堂", trigger: "change" }
        ],
        shopNo: [{ required: true, message: "请输入档口编号", trigger: "blur" }]
      },
      tableData: []
    };
  },
  mounted() {
    const that = this;
    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    this.userInfo = userInfo;
    that.common();
    that.tableData = DangKouList;
    that.price = DangKouInput;
    that.getSchool(userInfo);
  },
  methods: {
    common() {
      const that = this;
      this.$axios
        .get(that.url + "/admin/market/page", {
          params: {
            pageNo: 1,
            pageSize: 1000
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.marketList = res.data.data.records;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex % 3 === 0) {
          return {
            rowspan: 3,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    getShiTang() {
      const that = this;
      this.$axios
        .get(that.url + "/admin/market/list", {
          params: {
            deptId: that.ruleForm.schoolId
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.shitangList = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    getSchool() {
      const that = this;
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      this.$axios
        .get(that.url + "/admin/dept/list", {
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.schoolList = res.data.data;
            if (!!userInfo.deptId == false) {
            } else {
              //如果存在学校id
              that.ruleForm.schoolId = userInfo.deptId;
              that.getShiTang();
            }
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    resetData(id) {
      this.$refs["ruleForm"].resetFields();//先清空
      const that = this;
      that.getSchool();
      that.common();
      if (id) {
        this.id = id;
      }
      this.$axios
        .get(that.url + "/admin/shop/get/{id}", {
          params: {
            id
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.status == 200) {
            let data = res.data.data;
            that.ruleForm.shitangId = data.marketId;
            that.ruleForm.name = data.name;
            that.ruleForm.shopNo = data.shopNo;
            that.ruleForm.schoolId=data.deptId;
            that.ruleForm.limitCount=data.limitCount;
            that.ruleForm.limitAmount=data.limitAmount;

            that.getShiTang();
            let mealDtos = data.mealDtos;
            that.mealDtos = mealDtos;
            let currentIndex = 0;
            let inputData={};
            console.log(mealDtos)
            mealDtos.forEach((item, index) => {
              console.log(item.breakfast.price,item.breakfast.discPrice)

                that.price['student'+currentIndex]=item.breakfast.price;
                that.price['teacher'+currentIndex]=item.breakfast.discPrice;

                that.price['student'+(1+currentIndex)]=item.lunch.price;
                that.price['teacher'+(1+currentIndex)]=item.lunch.discPrice;

                that.price['student'+(2+currentIndex)]=item.dinner.price;
                that.price['teacher'+(2+currentIndex)]=item.dinner.discPrice;
                currentIndex+=3;

            })


          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    submitForm(formName) {
      const that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (that.id == "") {
            that.addSend();
          } else {
            that.updateSend();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    updateSend() {
      const that = this;
      that.upluadStatus=true;
      let arr = [];
      let arr2 = [];
      let obj = {};
      let obj2 = {};
      let data = Object.entries(this.price);

      data.forEach((item, index) => {
        if (item[0].slice(0, 7) == "student") {
          if (Number.parseInt(item[0].slice(7)) % 3 == 0) {
            //早餐

            obj["breakfast"] = {
              price: item[1]
            };
          } else if (Number.parseInt(item[0].slice(7)) % 3 == 1) {
            //午餐
            obj["lunch"] = {
              price: item[1]
            };
          } else if (Number.parseInt(item[0].slice(7)) % 3 == 2) {
            //晚餐
            obj["dinner"] = {
              price: item[1]
            };

            switch (index) {
              case 2:
                obj["weekday"] = 1;
                break;
              case 5:
                obj["weekday"] = 2;
                break;
              case 8:
                obj["weekday"] = 3;
                break;
              case 11:
                obj["weekday"] = 4;
                break;
              case 14:
                obj["weekday"] = 5;
                break;
              case 17:
                obj["weekday"] = 6;
                break;
              case 20:
                obj["weekday"] = 7;
                break;
            }

            arr.push(obj);
            obj = {};
          }

        }
        if (item[0].slice(0, 7) == "teacher") {
          if (Number.parseInt(item[0].slice(7)) % 3 == 0) {
            //早餐

            obj2["breakfast"] = {
              discPrice: item[1]
            };
          } else if (Number.parseInt(item[0].slice(7)) % 3 == 1) {
            //午餐
            obj2["lunch"] = {
              discPrice: item[1]
            };
          } else if (Number.parseInt(item[0].slice(7)) % 3 == 2) {
            //晚餐
            obj2["dinner"] = {
              discPrice: item[1]
            };
            arr2.push(obj2);
            obj2 = {};
          }
        }
      });

      // 合并两个数组
      let resultArr = [];
      let obj3 = {};
      arr.forEach((item1, index1) => {
        arr2.forEach((item2, index2) => {
          if (index1 == index2) {
            obj3["breakfast"] = { ...item1.breakfast, ...item2.breakfast };
            obj3["lunch"] = { ...item1.lunch, ...item2.lunch };
            obj3["dinner"] = { ...item1.dinner, ...item2.dinner };
            obj3["weekday"] = item1.weekday;
            resultArr.push(obj3);
            obj3 = {};
          }
        });
      });


      resultArr.forEach((item1, index1) => {
        that.mealDtos.forEach((item2, index2) => {
          if (item1.weekday == item2.weekday) {
            item1["mealId"] = item2.id; //生成mealId总
            item1["breakfast"]["productId"] = item2["breakfast"].id;
            item1["lunch"]["productId"] = item2["lunch"].id;
            item1["dinner"]["productId"] = item2["dinner"].id;
          }
        });
      });

      let resultData = {
        id: that.id,
        mealInfo: JSON.stringify(resultArr),
        marketId: that.ruleForm.shitangId,
        name: that.ruleForm.name,
        shopNo: that.ruleForm.shopNo,
        sysUserName: that.ruleForm.sysUserName,
        limitCount:that.ruleForm.limitCount,
        limitAmount:that.ruleForm.limitAmount,
      };

      this.$axios
        .post(
          that.url + "/admin/shop/saveOrUpdate",
          that.$qs.stringify(resultData),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          that.upluadStatus=false;
          if (res.status == 200) {
            if(res.data.code==200){
              if (that.id == "") {
                that.$message({
                  message: "添加成功",
                  type: "success"
                });
              } else {
                that.$message({
                  message:"修改成功",
                  type: "success"
                });
              }
              that.$emit("hideEdit", false);
            }else{
              that.$message({
                message: res.data.msg,
                type: "warning"
              });
            }
          } else {
            that.$message({
              message: res.statusText,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          that.upluadStatus=false;
          console.log(error);
        });
    },
    addSend() {
      const that = this;
      that.upluadStatus=true;
      let arr = [];
      let arr2 = [];
      let obj = {};
      let obj2 = {};
      let data = Object.entries(this.price);

      data.forEach((item, index) => {
        if (item[0].slice(0, 7) == "student") {
          if (Number.parseInt(item[0].slice(7)) % 3 == 0) {
            //早餐

            obj["breakfast"] = {
              price: item[1]
            };
          } else if (Number.parseInt(item[0].slice(7)) % 3 == 1) {
            //午餐
            obj["lunch"] = {
              price: item[1]
            };
          } else if (Number.parseInt(item[0].slice(7)) % 3 == 2) {
            //晚餐
            obj["dinner"] = {
              price: item[1]
            };

            switch (index) {
              case 2:
                obj["weekday"] = 1;
                break;
              case 5:
                obj["weekday"] = 2;
                break;
              case 8:
                obj["weekday"] = 3;
                break;
              case 11:
                obj["weekday"] = 4;
                break;
              case 14:
                obj["weekday"] = 5;
                break;
              case 17:
                obj["weekday"] = 6;
                break;
              case 20:
                obj["weekday"] = 7;
                break;
            }

            arr.push(obj);
            obj = {};
          }
          // console.log("学生");
        }
        if (item[0].slice(0, 7) == "teacher") {
          if (Number.parseInt(item[0].slice(7)) % 3 == 0) {
            //早餐

            obj2["breakfast"] = {
              discPrice: item[1]
            };
          } else if (Number.parseInt(item[0].slice(7)) % 3 == 1) {
            //午餐
            obj2["lunch"] = {
              discPrice: item[1]
            };
          } else if (Number.parseInt(item[0].slice(7)) % 3 == 2) {
            //晚餐
            obj2["dinner"] = {
              discPrice: item[1]
            };
            arr2.push(obj2);
            obj = {};
          }
        }
      });

      // 合并两个数组
      let resultArr = [];
      let obj3 = {};
      arr.forEach((item1, index1) => {
        arr2.forEach((item2, index2) => {
          if (index1 == index2) {
            obj3["breakfast"] = { ...item1.breakfast, ...item2.breakfast };
            obj3["lunch"] = { ...item1.lunch, ...item2.lunch };
            obj3["dinner"] = { ...item1.dinner, ...item2.dinner };
            obj3["weekday"] = item1.weekday;
            resultArr.push(obj3);
            obj3 = {};
          }
        });
      });

      let resultData = {
        mealInfo: JSON.stringify(resultArr),
        marketId: that.ruleForm.shitangId,
        name: that.ruleForm.name,
        shopNo: that.ruleForm.shopNo,
        sysUserName: JSON.parse(localStorage.getItem('userInfo')).name
      };

      this.$axios
        .post(
          that.url + "/admin/shop/saveOrUpdate",
          that.$qs.stringify(resultData),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          that.upluadStatus=false;
          if (res.status == 200) {
            if(res.data.code==200){
              if (that.id == "") {
                that.$message({
                  message: "添加成功",
                  type: "success"
                });
              } else {
                that.$message({
                  message:"修改成功",
                  type: "success"
                });
              }
              that.$emit("hideEdit", false);
            }else{
              that.$message({
                message: res.data.msg,
                type: "warning"
              });
            }
          } else {
            that.$message({
              message: res.statusText,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          that.upluadStatus=false;
          console.log(error);
        });
    },
    resetForm(formName) {
      this.ruleForm.id = "";
      this.id = "";//清空
      this.$refs[formName].resetFields();
      this.getSchool();
      this.price = DangKouInput;
      for (let key in this.price) {
        this.price[key] = "";
      }
    }
  }
};
</script>

<style scoped lang="scss">
.everyDaySame {
  display: flex;
  border: 1px solid #ebeef5;
  margin: 15px 0;

  p {
    width: 50px;
    padding-left: 20px;
  }
}

.content {
  padding: 0 5%;
}

.title {
  width: 50%;
}

.el-select {
  width: 50%;
}

.el-table {
  margin-top: 15px;
}

.el-date-editor {
  width: 100%;
}
</style>
